const { text } = require('body-parser')
let pool = require('../../mysql/pool')
let fs = require('fs')

module.exports = (req, res) => {
  let { username, userpassword } = req.body
  let querystr1 = 'select * from sessions'
  pool.query(querystr1, (err, result) => {
    if (err) return console.log(err.message)
    if (result.length === 0) {
      // 没登陆过进行登录
      let querystr1 = 'select * from user'
      pool.query(querystr1, (err, result) => {
        if (err) return console.log(err.message)
        // 判断用户是否存在
        let cunzai = false
        for (const index in result) {
          if (result[index].username == username && result[index].userpassword == userpassword) {
            cunzai = true
            break
          }
        }
        if (cunzai) {
          // 如果用户存在
          res.redirect('http://8.138.146.253:9000/html/index.html')
          let querystr2 = 'insert into sessions value("true")'
          pool.query(querystr2, (err, result) => {
            if (err) return console.log(err.message)
            console.log("插入sessions成功");
          })
        } else {
          // 如果用户不存在
          res.render('tip', { text: '没有该用户,请确保该用户已注册' })
        }

      })
    } else {
      // 登陆过
      res.render('tip', { text: "你已登录过无需再登录" })
      // fs.readFile('./public/html/index.html', function (err, data) {
      //   res.send(data.toString())
      // })
    }
  })
}


